import threading


# 全局变量
g_num = 0


# 对g_num进行加操作
def sum_num1():
    # 上锁
    mutex.acquire()

    for i in range(1000000):
        global g_num
        g_num += 1

    # 解锁
    mutex.release()

    print("g_num1:", g_num)


# 对g_num进行加操作
def sum_num2():
    # 上锁
    mutex.acquire()

    for i in range(1000000):
        global g_num
        g_num += 1

    # 解锁
    mutex.release()

    print("g_num2:", g_num)


if __name__ == '__main__':
    # 创建锁
    mutex = threading.Lock()
    # 创建子线程
    sum1_thread = threading.Thread(target=sum_num1)
    sum2_thread = threading.Thread(target=sum_num2)
    # 提示：加上互斥锁，那个线程抢到这个锁我们决定不了，那线程抢到锁哪个线程就先执行
    # 加上互斥锁多任务瞬间变成单任务，性能会下降，也就是说同⼀时刻只能有一个线程再执行
    # 启动线程
    sum1_thread.start()
    sum2_thread.start()